import json
from jsonpath_ng import parse

class JsonService:
    def __init__(self, file_path):
        """ 初始化，加载 JSON 文件 """
        self.file_path = file_path
        self.data = self._load_json()

    def _load_json(self):
        """ 读取 JSON 文件 """
        try:
            with open(self.file_path, 'r', encoding='utf-8') as file:
                return json.load(file)
        except (json.JSONDecodeError, FileNotFoundError):
            return {}  # 如果文件不存在或解析失败，返回空字典

    def _save_json(self):
        """ 保存 JSON 数据到文件 """
        with open(self.file_path, 'w', encoding='utf-8') as file:
            json.dump(self.data, file, indent=4, ensure_ascii=False)

    def read(self, json_path):
        """ 查询 JSON 数据 """
        jsonpath_expr = parse(json_path)
        return [match.value for match in jsonpath_expr.find(self.data)]

    def create(self, json_path, new_data):
        """ 在指定 JSONPath 位置插入数据 """
        jsonpath_expr = parse(json_path)
        matches = jsonpath_expr.find(self.data)
        if matches:
            for match in matches:
                if isinstance(match.value, list):  # 只能向数组插入数据
                    match.value.append(new_data)
                    self._save_json()
                    return True
                else:
                    return False
        else:
            # 如果没有匹配到路径，则创建一个新的
            jsonpath_expr = parse(json_path)
            parent_path = jsonpath_expr.left
            parent_matches = parent_path.find(self.data)
            if parent_matches:
                for match in parent_matches:
                    if isinstance(match.value, list):
                        match.value.append(new_data)
                        self._save_json()
                        return True
                    else:
                        match.value = new_data
                        self._save_json()
                        return True
            else:
                # 如果父路径也不存在，则创建整个路径
                keys = json_path.strip('$').split('.')
                current = self.data
                for key in keys[:-1]:
                    if key not in current:
                        current[key] = {}
                    current = current[key]
                if isinstance(current, dict):
                    current[keys[-1]] = [new_data]
                    self._save_json()
                    return True
        return False

    def update(self, json_path, new_value):
        """ 更新 JSONPath 指定的值 """
        jsonpath_expr = parse(json_path)
        matches = jsonpath_expr.find(self.data)
        if matches:
            for match in matches:
                match.path.update(self.data, new_value)
            self._save_json()
            return True
        return False

    def delete(self, json_path):
        """ 删除 JSONPath 指定的值 """
        jsonpath_expr = parse(json_path)
        matches = jsonpath_expr.find(self.data)
        if matches:
            for match in matches:
                match.path.delete(self.data)
            self._save_json()
            return True
        return False